package net.gz01.wallet.web.controller.customer;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import net.gz01.wallet.web.model.*;
import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Clear;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.redis.Redis;

import net.gz01.util.ZOLog;
import net.gz01.util.ZOMD5;
import net.gz01.wallet.common.WalletSMS;
import net.gz01.wallet.web.config.SystemConfig;
import net.gz01.wallet.web.controller.BaseController;
import net.gz01.wallet.web.interceptors.AuthInterceptor;
import net.gz01.wallet.web.interceptors.SessionTimeOutInterceptor;

@Clear({AuthInterceptor.class, SessionTimeOutInterceptor.class})
public class MainController extends BaseController{

	public void index() {
		String payUrl = getPara("payUrl");
		String api = getPara("api");
		if(StringUtils.isNotEmpty(api) && "api".equals(api)){
			String userName = getPara("login");
			String type = getPara("loginType");
			MerchUser merchUser = MerchUser.dao.selectByUserName(userName, type);
			if(merchUser !=null){
				getSession().setAttribute(MerchUser.SessionKey, merchUser);
			}
		}
		if(StringUtils.isEmpty(payUrl)){
			payUrl = "/customer/index";
		}
		MerchUser merchUser = (MerchUser) getSession().getAttribute(MerchUser.SessionKey);
		if (merchUser == null) {
			redirect("/customer/login");
			return;
		}
		Merch merch = Merch.dao.selectByMerchCode(merchUser.getMerchCode());
		if (merch == null) {
			renderFail("该用户所属商户不存在，请联系管理员");
			return;
		}

		if(StringUtils.isEmpty(merch.getAccountType())){
			merch.setAccountType("1");
			merch.update();
		}

		//如果没有实名网签，必须实名网签后才能使用钱包系统
		if(!merch.getIsSign() || !merch.getIsVerify() || StringUtils.isEmpty(merchUser.getPayPassword()) ||
				merchUser.getPayPassword().equals(merchUser.getPassword())){
			//调用实名网签接口
//			redirect("/api/netSign?me=me&userName=" + merchUser.getUserName() + "&passWord=" +
//					merchUser.getPassword() + "&type=" + merch.getUserType());

			HeTongConfig heTongConfig =  HeTongConfig.dao.selectByEnable();
			if(heTongConfig == null){
				renderText("没有开启合同功能！");
				return;
			}
			setAttr("merchUser", merchUser);
			setAttr("isVerify", merch.getIsVerify());
			setAttr("isSign", merch.getIsSign());
			setAttr("useType", merch.getAccountType());
			setAttr("heTongConfig", heTongConfig);
			setAttr("loginType", merch.getUserType());
			setAttr("inCome", merch.getUserType());
			if(StringUtils.isNotEmpty(payUrl)){
				setAttr("payUrl", payUrl);
			}
			setAttr("hetongUrl", SystemConfig.config.get("myUrl") + heTongConfig.getPdfUrl());
			setAttr("isNotEmptyPayPassword", (StringUtils.isNotEmpty(merchUser.getPayPassword()) &&
					!merchUser.getPayPassword().equals(merchUser.getPassword())));
			setAttr("type",merch.getAccountType().equals("1")?"personal":"company");
			render("agreement.html");
			return;
		}

		// 收款账户规则
		YouliAccountRule rule = YouliAccountRule.dao.findById(merch.getYouliAccountRuleId());
		// 收款账户
		List<YouliAccount> youliAccountList = new ArrayList<YouliAccount>();
		if (rule != null) {
			String youliAccountIds = rule.getYouliAccountId();
			if (StrKit.notBlank(youliAccountIds)) {
				Object[] ids = youliAccountIds.split(",");
				if (ids != null && ids.length > 0) {
					youliAccountList = YouliAccount.dao.selectByIds(ids);
				}
			}
		}
		// 通知
		setAttr("notices", Notice.dao.selectNoticeTitle());
		// 友利收款账户
		setAttr("youliAccountList", youliAccountList);
		// 钱包账户
		setAttr("account", Account.dao.select(merch.getCode()));
		setAttr("signPdf", merch.getViewpdfUrl());
		setAttr("realName", merch.getLegalPerson());
		List< Dictionary > userKJList = Dictionary.dao.selectByParentKey("userkuaijie");
		setAttr("userKJList", userKJList);
		render("index.html");
		/*if (merch.getIsSign() && merch.getIsVerify()) {
			redirect("agreement");
		} else {
		}*/
	}

	public void login() throws Exception{
		if ("GET".equalsIgnoreCase(getRequest().getMethod())) {
			render("login.html");
			return;
		}
		String loginType = getPara("loginType");
		String phoneNo = getPara("phoneNo");
		String smscode = getPara("smscode");

		if(!"1".equals(loginType) && !"2".equals(loginType)){
			renderFail("不支持的登录方式");
			return;
		}
		if ("777777".equals(smscode) && "15975508712".equals(phoneNo)) {

		}else {
			String code =  Redis.use().get(WalletSMS.REDIS_PREFIX + phoneNo);
			if(code == null){
				renderFail("短信验证码未获取或已过期");
				return;
			}
			if(!code.equals(smscode)){
				renderFail("短信验证码错误");
				return;
			}
		}
		MerchUser loginUser = MerchUser.dao.selectByUserName(phoneNo, loginType);
		if(loginUser==null){
			renderFail("手机号/短信验证码错误");
			return;
		}
		if(loginUser.getEnable() == false){
			renderMsg(2, "用户被禁用");
			return;
		}
		getSession().setAttribute(MerchUser.SessionKey, loginUser);
		renderSuccess();
	}

	/**
	 * 获取验证码
	 */
	public void getCaptchaCode(){
		renderCaptcha();
	}


	public void logout(){
		getSession().removeAttribute(MerchUser.SessionKey);
		redirect("/customer/login");
	}

	public void agreement() {
		setAttr("type", getPara());
		render("agreement.html");
	}

	public void errorMsg(){
		String msg = getPara("msg");
		setAttr("msg", msg);
		render("errormsg.html");
	}

	public void setPayPassword(){
		String payUrl = getPara("payUrl");
		if(StringUtils.isEmpty(payUrl)){
			payUrl = "/customer/index";
		}
		String userName = getPara("userName");
		String phone = getPara("phone");
		String loginType = getPara("loginType");
		String payPassword1 = getPara("payPassword1");
		String payPassword2 = getPara("payPassword2");
		String code = getPara("code");

		//if (!"777777".equals(code))
		{
			String send = Redis.use().get(WalletSMS.REDIS_PREFIX + phone);
			ZOLog.api.info("redis 保存的验证码:" + send);
			if (StrKit.isBlank(code) || !send.equals(code)) {
				renderFail("验证码错误");
				return;
			}
		}

		if(!payPassword1.equals(payPassword2)){
			renderFail("error:"+ "两次密码不一致!");
			return;
		}

		MerchUser merchUser =  MerchUser.dao.selectByUserName(userName, loginType);
		if(merchUser==null){
			renderFail("该用户不存在:，请联系管理员:" + userName);
			return;
		}
		Merch merch = Merch.dao.selectByMerchCode(merchUser.getMerchCode());
		if (merch == null) {
			renderFail("该用户所属商户不存在，请联系管理员");
			return;
		}
		merchUser.setPayPassword(ZOMD5.codeFor(payPassword1));
		merchUser.update();

		ZOLog.api.info("设置成功:" + userName + ":" + payPassword1 + "," + payPassword2);

		getSession().setAttribute(MerchUser.SessionKey, merchUser);
		//redirect(payUrl);
		renderSuccess();
		return;

//		{
//			//调用实名网签接口
////			redirect("/api/netSign?me=me&userName=" + merchUser.getUserName() + "&passWord=" +
////					merchUser.getPassword() + "&type=" + merch.getUserType());
//
//			HeTongConfig heTongConfig =  HeTongConfig.dao.selectByEnable();
//			setAttr("merchUser", merchUser);
//			setAttr("isVerify", merch.getIsVerify());
//			setAttr("isSign", merch.getIsSign());
//			setAttr("useType", merch.getAccountType());
//			if(StringUtils.isNotEmpty(payUrl)){
//				setAttr("payUrl", payUrl);
//			}
//			setAttr("heTongConfig", heTongConfig);
//			setAttr("hetongUrl", SystemConfig.config.get("myUrl") + heTongConfig.getPdfUrl());
//			setAttr("isNotEmptyPayPassword", (StringUtils.isNotEmpty(merchUser.getPayPassword()) &&
//					!merchUser.getPayPassword().equals(merchUser.getPassword())));
//			setAttr("type",merch.getAccountType().equals("1")?"personal":"company");
//			render("agreement.html");
//		}
	}


	/**
	 * 发送短信验证码
	 */
	public void sendsms() {
		String phoneNo = getPara("phoneNo");
		if (phoneNo == null || phoneNo.length() != 11) {
			renderFail("手机号无效");
			return;
		}
		// 限制发送间隔，防止短信爆破，待redis中的验证码失效后才允许下一次发送
		if(Redis.use().get(WalletSMS.REDIS_PREFIX + phoneNo) != null){
			renderFail("请勿频繁请求，稍后再试");
			return;
		}

		StringBuilder buff = new StringBuilder();
		Random rd = new Random();
		for (int i = 0; i < 6; i++) {
			buff.append(String.valueOf(rd.nextInt(10)));
		}
		String code = buff.toString();
		Redis.use().setex(WalletSMS.REDIS_PREFIX+phoneNo, 60, code);
		JSONObject result = WalletSMS.sendForLogin(phoneNo, code);
		if ("OK".equals(result.getString("Code"))) {
			renderSuccess("验证码已发送成功");
		} else {
			renderFail(result.getString("Message"));
		}
	}

}
